#include "../utils/array.h"
#include "../encoding/utf8.h"
#include "pe_file.h"

namespace nsshare
{
namespace utils
{

bool PEFile::GetFileVersion(const char * file, uint64_t & ver)
{
    using namespace encoding;

    wchar_t filename16[kMaxPath];

    if(!UTF8::Decode(file, -1, filename16, kMaxPath))
        return false;

    DWORD ver_size = 0;
    DWORD handle = 0;

    ver_size = ::GetFileVersionInfoSize(filename16, &handle);
    if (ver_size == 0)
        return false;

    ScopeArray<uint8_t> ver_buffer;
    if(!ver_buffer.init(ver_size))
        return false;

    if(!::GetFileVersionInfo(filename16, 0, ver_size, ver_buffer))
        return false;

    VS_FIXEDFILEINFO * info_ptr = 0;
    uint32_t info_len = 0;
    if(!::VerQueryValue(ver_buffer, L"\\", (void **)&info_ptr, &info_len))
        return false;

    ver = info_ptr->dwFileVersionMS;
    ver <<= 32;
    ver |= info_ptr->dwFileVersionLS;
    return true;
}

}
}